<?php
namespace Home\Controller;

use Home\Model\BonusModel;
use Think\Controller;

class MatchingController extends CommonController
{

    public function index()
    {
        $this->display();
    }

    protected function nextmatch()
    {

    }

    protected function match()
    {
        $db_match = M('matching');
        $info = $db_match->find();
        if (empty($info)) {
            $data['mc_order'] = 1;
            $data['mc_time'] = time();
            $db_match->add($data);
        }
    }
    public function is_wallert(){
        is_qx(1);
        $db_match = M('matching');
        $m_info = $db_match->order('mc_id desc')->limit(1)->select()[0];
        $db_tg=M('tgbz');
        $where['zt'] = 1;
        $where['qr_zt'] = 1;
        $where['qr_zt'] = 1;
        $where['tg_wallet']=0;
//        dump($m_info['mc_order']);
//        $where['tg_order'] =$m_info['mc_order'];

        $tg_list=$db_tg->where($where)->select();
        if(!empty($tg_list)){return true;}
    }
    protected function setInc($username,$fieldname,$num){
        $db_user=M('user');
        $where['UE_account']=$username;
        if($username==""){
            die("<script>alert('用户名为空，请联系管理员！');parent.location.reload();</script>");
//			dump('用户名不能为空！');
        }
        $uinfo=$db_user->where($where)->find();
        if(empty($uinfo)){
            return;
            die("<script>alert('用户信息为空，请联系管理员！');parent.location.reload();</script>");
//			dump('用户信息不能为空！');
        }else{
            $db_user->where($where)->setInc($fieldname,$num);
        }
    }

    //钱包结算
    public function wallert_settlement(){
        //获取最后一期
//        $db_match = M('matching');
//        $m_info = $this->getmatch_info();

//        ignore_user_abort();
        //即使Client断开(如关掉浏览器)，PHP脚本也可以继续执行.
        set_time_limit(0);
        //执行时间为无限制，php默认的执行时间是30秒，通过set_time_limit(0)可以让程序无限制的执行下去
        ini_set('memory_limit', '1G');

        $db_tg=M('tgbz');
        $where['zt'] = 1;
        $where['qr_zt'] = 1;
        $where['tg_wallet']=0;

        $tg_list=$db_tg->where($where)->select();
        if(empty($tg_list[0])){msg('没有钱包需要结算！');}

        foreach ($tg_list as $tg_info){
            if($tg_info['tg_wallet']==0 or empty($tg_info['tg_wallet']) ){

                if($tg_info['jb']==5000){
                    $tg_info['tg_wallet']=6000;
//                    $this->setInc($tg_info['user'],'UE_money',$tg_info['tg_wallet']);

                    $this->add_income($tg_info['user'],6000,'jb','ax');
                }elseif($tg_info['jb']==1000){
                    $tg_info['tg_wallet']=1200;
                    $this->add_income($tg_info['user'],1200,'jb','ax');
//                    $this->setInc($tg_info['user'],'UE_money',$tg_info['tg_wallet']);
                }elseif($tg_info['jb']==3000){
                    $tg_info['tg_wallet']=3600;
                    $this->add_income($tg_info['user'],3600,'jb','ax');
//                    $this->setInc($tg_info['user'],'UE_money',$tg_info['tg_wallet']);
                }
                $db_tg->save($tg_info);

//                $this->tj($tg_info['id']);

            }

        }
//        $this->success('已结算成功！');
//        die("<script>alert('结算成功！');history.back(-1);</script>");
        die("<script>alert('结算成功！');history.back(-1);</script>");
//        $this->success('已结算完毕！');
    }




    //当前处理
    public function setmatch(){
        is_qx(1);

//        ignore_user_abort();
        //即使Client断开(如关掉浏览器)，PHP脚本也可以继续执行.
        set_time_limit(0);
        //执行时间为无限制，php默认的执行时间是30秒，通过set_time_limit(0)可以让程序无限制的执行下去
        ini_set('memory_limit', '1G');

        if (IS_POST) {
            $db_tg = M('tgbz');
            $db_js = M('jsbz');
            $where['zt'] = array('neq', 1);
            $where['qr_zt'] = array('neq', 1);
//            $where['tg_status'] = array('eq', 1);
//            $where['js_status'] = array('eq', 1);

            $db_tg->where($where)-> setField('tg_status',0);
            $db_js->where($where)->setField('js_status',0);

            $tg_total = $db_tg->where($where)->sum('jb');
            $js_total = $db_js->where($where)->sum('jb');

            $max=$js_total;
            if($js_total>$tg_total){
                $max=$tg_total;
            }

            $m_info = $this->getmatch_info();
            $db_match = M('matching');
            $last_minfo= $db_match->where(array('mc_order'=>$m_info['mc_order']))->find();
            $list=  $db_js->where($where)->order('id asc')->select();

            //收款
            $count_money=0;
//            dump(date('Y-m-d H:i:s',$last_minfo['mc_time']));
            foreach ($list as $info){

                $uinfo=M('user')->where(array('ue_status'=>0,'ue_account'=>$info['user']))->find();
                if(empty($uinfo)){
                    continue;
                }


                $tginfo=$db_tg->where(array('user'=>$info['user'],'zt'=> array('neq', 1),'qr_zt'=> array('neq', 1)))->find();
                if(empty($tginfo)){
//                    echo '不在排单用户：'.$info['user']."<br/>";
                    continue;
                }
                $count_money+=$info['jb'];
                if($count_money>$max){
                    break;
                }
                $info['js_status']=1;
                $db_js->save($info);
            }
            $max=$count_money;

            //打款
            $count_money=0;
            $list=  $db_tg->where($where)->order('id asc')->select();
            foreach ($list as $info){
                $uinfo=M('user')->where(array('ue_status'=>0,'ue_account'=>$info['user']))->find();
                if(empty($uinfo)){
                    continue;
                }

                $count_money+=$info['jb'];

                $info['tg_status']=1;
                $db_tg->save($info);
                if($count_money>$max){
                    break;
                }
            }


            $this->success('处理成功！');
        }
    }
    public function add_tgbz(){
//        ignore_user_abort();
        //即使Client断开(如关掉浏览器)，PHP脚本也可以继续执行.
        set_time_limit(0);
        //执行时间为无限制，php默认的执行时间是30秒，通过set_time_limit(0)可以让程序无限制的执行下去
        ini_set('memory_limit', '1G');
        $user = M('user'); // 實例化User對象

//        $db_match = M('matching');
//        $m_info = $db_match->order('mc_id desc')->limit(1)->select()[0];
//        $map['user_latematch'] = array('elt',$m_info['mc_order']-5);
//        $map['UE_status']=0;
//        $user_list=$user->where($map)->select();
//dump(count($user_list));
//        $count=1;
//        $js_count=1;
        $db_tgbz=M('tgbz');

        $tgbz_list= $db_tgbz->where(array('zt'=>0,'qr_zt'=>0,'date'=>array('gt','2016-10-10 00:00:00')))->select();

        foreach ($tgbz_list as $tgbz_info){
            $is_tg=$db_tgbz->where(array('memo'=>1,'user'=>$tgbz_info['user']))->find();
            if(empty($is_tg)){
                $data['user']=$tgbz_info['user'];
                $data['jb']=5000;
                $data['user_nc']=$tgbz_info['user_nc'];
                $data['user_tjr']=$tgbz_info['user_tjr'];
                $data['date']=date ( 'Y-m-d H:i:s', time () );
                $data['zt']=0;
                $data['qr_zt']=0;
                $data['memo']=1;
                M('tgbz')->add($data);
            }
        }

        dump(count($tgbz_list));
        dump("加单成功！");
//        foreach ($user_list as $uinfo){
//            $db_tgbz->where(array('zt'=>0,'qr_zt'=>0,'user'=>$uinfo['ue_account']))->find();
//            if(empty($db_tgbz)){
//                $count+=1;
////                $data['user']=$user['ue_account'];
////                $data['jb']=5000;
////                $data['user_nc']=$user['ue_theme'];
////                $data['user_tjr']=$user['ue_accname'];
////                $data['date']=date ( 'Y-m-d H:i:s', time () );
////                $data['zt']=0;
////                $data['qr_zt']=0;
////                M('tgbz')->add($data);
//            }
//            $js_count+=1;
//        }
//        dump($count);
//        dump($js_count);
    }
    public function getmatch_info(){
        $db_match = M('matching');
        $m_info = $db_match->order('mc_id desc')->limit(1)->select()[0];
        return $m_info;
    }

    //自动匹配
    public function domatch()
    {
        is_qx(1);
//        ignore_user_abort();
        //即使Client断开(如关掉浏览器)，PHP脚本也可以继续执行.
        set_time_limit(0);
        //执行时间为无限制，php默认的执行时间是30秒，通过set_time_limit(0)可以让程序无限制的执行下去
        ini_set('memory_limit', '1G');
        if (IS_POST) {
            if($this->is_wallert()){
                msg("请先钱包结算!");
            }

            $db_tg = M('tgbz');
            $where['zt'] = array('neq', 1);
            $where['tg_status'] = array('eq', 1);
            $where['js_status'] = array('eq', 1);
            $tg_total = $db_tg->where($where)->sum('jb');
            slog($tg_total);

            $db_js = M('jsbz');
            $js_total = $db_js->where($where)->sum('jb');
            slog($js_total);

            if ($js_total != $tg_total ) {
                $this->success('');
                msg('两边金额不相等，无法匹配！');
            }
            if ($tg_total <= 0 or $js_total <= 0) {
                msg('两边金额不能为零,匹配失败！');
            }


            //获取本期期数
            $db_match = M('matching');
            $m_info = $this->getmatch_info();
            $data=null;
            $data['mc_jstotal']=$js_total;
            $data['mc_tgtotal']=$tg_total;
            $data['mc_time'] = time();
            if (empty($m_info)) {
                $data['mc_order'] = 1;
                slog('设置第一期');
            } else {

                $data['mc_order'] =$m_info['mc_order']+1;
            }
            $ret_id = $db_match->add($data);
            $m_info = $this->getmatch_info();
            $order=$m_info['mc_order'];
            slog('第'.$order.'期');


            //获取匹配信息
            $js_list = $db_js->where($where)->select();
            $tg_list = $db_tg->where($where)->select();

            //开始自动匹配
            $db_pp = M('ppdd');
            $n = 0;
            $tg_temp = $tg_list[$n];
            $js_temp = null;
            $money = 0;
            foreach ($js_list as $js_info) {//遍历接受帮助
                $js_temp = $js_info;
                while ($js_temp['jb'] > 0) {
                    if ($tg_temp['jb'] == 0) {//遍历提供帮助
                        $tg_temp = $tg_list[++$n];
                        if(empty($tg_temp)){break;}
                    }

                    //设置交易金额
                    if ($js_temp['jb'] >= $tg_temp['jb']) {
                        $money = $tg_temp['jb'];
                        $js_temp['jb'] = $js_temp['jb'] - $money;
                        $tg_temp['jb'] = 0;
                    } else {
                        $money = $js_temp['jb'];
                        $tg_temp['jb'] = $tg_temp['jb'] - $money;
                        $js_temp['jb'] = 0;
                    }

                    //设置已匹配成功 接受帮助、提供帮助表
                    if ($js_temp['jb'] == 0) {
                        M('jsbz')->where(array('id' => $js_temp['id'], 'zt' => '0'))->save(array('zt' => '1','js_order'=>$order));
                    }
                    if ($tg_temp['jb'] == 0) {
                        M('tgbz')->where(array('id' => $tg_temp['id'], 'zt' => '0'))->save(array('zt' => '1','tg_order'=>$order));
                    }

                    //添加交易记录
                    $data_add['p_id'] = $tg_temp['id'];
                    $data_add['g_id'] = $js_temp['id'];
                    $data_add['jb'] = $money;
                    $data_add['p_user'] = $tg_temp['user'];
                    $data_add['g_user'] = $js_temp['user'];
                    $data_add['date'] = date('Y-m-d H:i:s', time());
                    $data_add['zt'] = '0';
                    $data_add['pic'] = '0';
                    $data_add['order'] = $order;
                    $db_pp->add($data_add);
                }
            }

            //给新用户添加匹配信息以及其它信息
            $newinfo=getuserinfo($tg_temp['user']);
            if(empty($newinfo)){log($tg_temp['user'] . '用户信息不存在！'); }
            if(!empty($newinfo) && ($newinfo['user_firstmatch']==null or $newinfo['user_firstmatch']==0)){

            }


            //设置用户匹配信息
            $save=null;
            $j=0;
            foreach ($tg_list as $info) {
                $uinfo=getuserinfo($info['user']);
//                $uinfo=M('user')->where(array('UE_account'=>$info['user']))->find();
                if ($uinfo['user_firstmatch'] == 0 or $uinfo['user_firstmatch']==null) {
                    $save['user_firstmatch']=$order;
                    $save['user_latematch']=$order;
                    $save['user_nummatch']=1;
//                    $this->addceng($uinfo);
                    M('user')->where(array('UE_account'=>$info['user']))->save($save);

                }
                elseif($uinfo['user_latematch']!=$order){
                    $uinfo['user_latematch']=$order;
                    $uinfo['user_nummatch']++;//匹配次数加一
                    M('user')->save($uinfo);
                }

                $j++;
                if($j>$n){break;}
//            M('user')->where(array('id'=>$js_temp['id'],'zt'=>'0'))->save(array('zt'=>'1'));
            }

            $this->success('匹配成功！');
        }
    }

    public function yhuser($id=1){
        $db_user=M('user');
        $listuinfo=$db_user->limit($id,$id+200)->select();

//        if(count($listuinfo)<=0){
//            die("<script>alert('数据优化成功');</script>");
//        }
        $n=200;
        foreach ($listuinfo as $uinfo){
            $this->addceng($uinfo);
            $n--;
//            dump($n);
            if($n<=0){
                break;
            }
        }
        if($id>10000){
            die("<script>alert('数据优化成功');</script>");
        }
        redirect(U('Matching/yh',array('id'=>$id+200)));
//                die("<script>alert('数据优化成功');</script>");
    }

    //优化数据
    public function yh($id=0){
        $order_info=$this->getmatch_info();
        $order=$order_info['mc_order'];
        $where['tg_order']=$order;
        $tglist=M('tgbz')->where($where)->order('id asc')->limit($id,500000)->select();

        $n=0;

        foreach ($tglist as $info){
            $uinfo=getuserinfo($info['user']);
//            dump($uinfo);

            if(!empty($uinfo)){
                if ($uinfo['user_firstmatch'] == 0 or $uinfo['user_firstmatch']==null) {
                    $uinfo['user_firstmatch']=$order;
                    $uinfo['user_latematch']=$order;
                    $uinfo['user_nummatch']=1;

                    M('user')->where(array('UE_account'=>$info['user']))->save($uinfo);
//                    $this->addceng($uinfo);
                    $n++;
    //                dump($n);
                }
                elseif($uinfo['user_latematch']!=$order && $uinfo['user_latematch']<$order){

                    if(($uinfo['user_latematch']+1)==$order){
                        $uinfo['user_nummatch']++;
                    }else{
                        $uinfo['user_nummatch']=1;
                    }
                    $uinfo['user_latematch']=$order;
                    //匹配次数加一
                    M('user')->where(array('UE_account'=>$info['user']))->save($uinfo);
                }
            }
            if($n>100){
//                dump($n);
//                break;
                redirect(U('Matching/yh',array('id'=>$id+100)));
            }
        }

        die("<script>alert('数据优化成功');history.back(-1);</script>");
//        die("<script>alert('数据优化成功');</script>");
//        dump($order);
    }
    //添加用户推荐关系
    protected function addceng($uinfo)
    {
        $tinfo = getuserinfo($uinfo['ue_accname']);
        $ceng = 1;
        $n=300;
        while (!empty($tinfo)) {

            $ceng_where['node_user']= $uinfo['ue_account'];
            $ceng_where['node_tj_user']= $tinfo['ue_account'];
            if($uinfo['ue_account']==$tinfo['ue_account']){
                break;
            }
            $cengInfo=M('ceng')->where($ceng_where)->find();
//            $cengInfo=null;
            if(empty($cengInfo)){
                $data['node_user'] = $uinfo['ue_account'];
                $data['node_tj_user'] = $tinfo['ue_account'];
                $data['node_ceng'] = $ceng;
                $data['node_num'] = 0;
                $data['node_time'] = time();
                M('ceng')->add($data);
            }
            $ceng++;
            $n--;

            if(empty($tinfo['ue_accname']) || $tinfo['ue_accname']==""){
                break;
            }
            $tinfo = getuserinfo($tinfo['ue_accname']);
            if($n<=0){
                dump('等级太多');
                break;
            }
        }
    }

    protected function log($str){
        dump($str);
    }

    //................推荐奖
    function tj($p_id){
        $set=get_set();
        $tj_num=$set['tj_num'];
        //验证是否开启推荐奖
        if($tj_num<=0){dumplog('推荐奖未开启',2);return;}

        $tg_info=M('tgbz')->where(array('id'=>$p_id,'zt'=>1,'qr_zt'=>1))->find();if(empty($tg_info)){dumplog('获取提供帮助信息不存在！',2);return;}

//        dump($tg_info['user']);

        //判断是否完成全部支付完成
        $money=$tg_info['jb'];
        $pd_money=M('ppdd')->where(array('p_id'=>$tg_info['id']))->sum('jb');
        if($money!=$pd_money){dumplog('提供帮助未全部完成！',2);return;}

        //获取打款人信息
        $tg_uinfo=getuserinfo($tg_info['user']);if(empty($tg_uinfo)){dumplog('打款人信息不存在！',2);return;}

        //获取期数
        $order=$tg_uinfo['user_latematch'];
        if($tg_uinfo['user_latematch']!=$tg_info['tg_order']){dumplog($tg_info['id'].'期数错误！',2);return;}

        //已经参加前五次都不给推荐奖
        if($tg_uinfo['user_firstmatch']<=5){
            return;
        }


//        if($order<=0 or $order==null){
//            dumplog($tg_info['id']);dumplog('期数错误！');return;
//        }

        //获取推荐人列表
        $c_where['node_user']=$tg_info['user'];
        $c_where['node_ceng']=array('elt',$tj_num);
        $listinfo=M('ceng')->where($c_where)->select();
        if(empty($listinfo)){dumplog($tg_info['user'] . '没有直推人！',2); return;}

//        dump($tg_info['user']);
//        dump(count($listinfo));

        foreach ($listinfo as $node_info){
            $ceng=$node_info['node_ceng'];
            $bl=$set['tj'][$ceng];

            if($ceng==1 && ($tg_uinfo['user_firstmatch']!=$tg_uinfo['user_latematch'] || $tg_uinfo['user_firstmatch']<=0)){continue;}

            $zt_uinfo=getuserinfo($node_info['node_tj_user']);

            //验证是否参加匹配
            $pd_tg_info=M('ppdd')->where(array('p_user'=>$node_info['node_tj_user'],'order'=>$order))->find();
            if(empty($pd_tg_info)){dumplog($node_info['node_tj_user'].'没有参加' .$order . '期匹配！',2);continue;}

            //验证推荐人是否连续参加匹配
            if($ceng!=1){
                $lx_num=$tg_uinfo['user_firstmatch']+$zt_uinfo['user_nummatch']-1;
                if($lx_num<$zt_uinfo['user_latematch']){dumplog($node_info['node_tj_user'].'不是连续参加',2);continue;}
            }


            //获得该用户推荐奖次数
            $run_num=$set['tj_run'][$ceng];

//            dump($ceng . '层 次数:' . $run_num);
            $get_count=M('user_jl')->where(array('fromuser'=>$tg_info['user'],'user'=>$node_info['node_tj_user']))->count();
            if($get_count>=$run_num){dumplog($tg_info['user'] . '用户的' . '已经获得'. $run_num .'次数',2);continue;}

            //验证是否为这期最小金额（第一层推荐奖）
            if($ceng==1){
                $first_ulist=M('user')->where(array('user_firstmatch'=>$tg_info['tg_order'],'UE_accName'=>$node_info['node_tj_user']))->field('UE_account')-> select();
                $aa=null;
                foreach ($first_ulist as $first_uinfo){
                    $aa[]=$first_uinfo['ue_account'];
                }
//                dump($aa);
                if(empty($aa)){dumplog('第一层无推荐人信息',2);return;}

                $first_where['tg_order']=$tg_info['tg_order'];
                $first_where['user_tjr']=array('IN',$aa);
                $first_tglist=M('tgbz')->where($first_where)->select();
                foreach ($first_tglist as $tg){
                    if($money>$tg['jb']){
                        dumplog('该提供帮助不是最小金额',2);  return;
                    }
                }
            }

            //写入推荐信息
            $data['user']=$node_info['node_tj_user'];
            $data['date']= date ( 'Y-m-d H:i:s', time ()); //操作时间
            $data['zt']=1;
            $data['jb']=$money;
            $data['r_id']=$tg_info['id'];
            $data['jj']=$money*$bl/100;
            $data['order']=$order;
            $data['ceng']=$ceng;
            $data['fromuser']=$tg_info['user'];
            $data['ds']=1;
            $data['note']='C钱包'. ($bl) .'%';
            M('user_jl')->add($data);

            $this->add_income($zt_uinfo['ue_account'],$data['jj'],'tj','tj');
        }
    }


    protected function add_income($username,$money,$money_type,$datatype){
        $uinfo=getuserinfo($username);
        if(empty($uinfo)){dumplog('添加收入 用户信息为空！');}
        $record3 ["UG_type"] = $money_type;
        switch ($money_type){
            case 'jb':
                $record3 ["UG_allGet"] = $uinfo['ue_money'];
                $uinfo['ue_money']+=$money;
//                M('user')->save($uinfo);
                M('user')->where(array('UE_ID'=>$uinfo['ue_id']))->save(array('UE_money'=>$uinfo['ue_money']));
                $record3 ["UG_balance"] = $uinfo['ue_money'];
                break;
            case 'tj':
                $record3 ["UG_allGet"] = $uinfo['tj_he'];
                $uinfo['tj_he']=intval( $uinfo['tj_he'])+ $money;
                M('user')->where(array('UE_ID'=>$uinfo['ue_id']))->save(array('tj_he'=>$uinfo['tj_he']));
                $record3 ["UG_balance"] = $uinfo['tj_he'];
                dumplog('获得推荐奖:'.$money,2);
                break;
            case 'jhb':
                $record3 ["UG_allGet"] = $uinfo['user_jhb'];
                $uinfo['user_jhb']+=$money;
                M('user')->where(array('UE_ID'=>$uinfo['ue_id']))->save(array('user_jhb'=>$uinfo['user_jhb']));
                $record3 ["UG_balance"] = $uinfo['user_jhb'];
                break;
        }

        $record3 ["UG_dataType"] =$datatype;
        switch ($datatype){
            case 'xtzs':
                $record3 ["UG_note"] = '系统操作';
                break;
            case 'jsbz':
                $record3 ["UG_note"] = '接受帮助扣款';
                break;
            case 'tj':
                $record3 ["UG_note"] = '推荐奖励';
                break;
            case 'ax':
                $record3 ["UG_note"] = '爱心奖励';
                break;
            case 'tgbz':
                $record3 ["UG_note"] = '提供帮助扣除';
                break;
        }

        $record3 ["UG_account"] = $username; // 登入转出账户
		$record3 ["UG_money"] = $money;
		$record3["UG_getTime"]= date ( 'Y-m-d H:i:s', time () ); //操作时间
		$reg4 = M ( 'userget' )->add ( $record3 );
    }


    //验证用户在本期是否拿到过推荐奖
    protected function check_tj_ceng($username,$order,$ceng){
        $info=M('user_jl')->where(array('user'=>$username,'order'=>$order,'ceng'=>$ceng));
        if(empty($info)){
            return false;
        }else{
            return true;
        }
    }

    //获得推荐人拿到次数
    protected  function get_tj_count($tj_username,$fromuser,$order){
        $count=M('user_jl')->where(array('user'=>$tj_username,'$fromuser'=>$fromuser,'order'=>$order));
        return $count;
    }

    //获取用户所有直推人在该期提供帮助金额最小值
    protected  function get_tj_min($username,$order){

        $list=M('user')->table('ot_user user,ot_tgbz tgbz')->where('user.ue_account=tgbz.user')
            ->where(array('user.ue_account'=>$username,'user.user_latematch'=>$order,'tgbz.tg_order'=>$order))
            ->select();
        dump(count($list));
        slog($list);
//		$ulist=M('user')->where(array('ue_account'=>$username,'user_latematch'=>$order));

        $min=$list[0]['jb'];
        foreach ($list as $info){
            if($info['jb']<$min){
                $min=$info['jb'];
            }
        }
        dump($min);
        return $min;
    }

}